package com.pan.frame;

import com.pan.server.MyServer;

import javax.swing.*;
import java.awt.*;

public class WaitConnectFrame {

    private String password;
    private MyServer myServer;
    public WaitConnectFrame(MyServer myServer,String password) {

        this.password = password;
        this.myServer = myServer;
    }

    private JFrame frame;

    private JLabel titleLabel;
    private JLabel tipsLabel;
    private JLabel waitTimeLabel;
    private JButton quitBtn;

    public void init() {
        frame = new JFrame("Pan.Qi.An");
        frame.setLayout(null);
        frame.setSize(400, 400);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        titleLabel = new JLabel("等待链接");
        titleLabel.setFont(new Font("SimSun",Font.BOLD,28));
        titleLabel.setBounds(120,40,200,80);
        frame.add(titleLabel);

        tipsLabel = new JLabel("房间密码：" + password + "");
        tipsLabel.setBounds(60, 140, 300, 40);
        tipsLabel.setFont(new Font("SimSun", Font.PLAIN, 24));
        frame.add(tipsLabel);


        waitTimeLabel = new JLabel("等待对方：0 秒");
        waitTimeLabel.setBounds(60, 200, 300, 40);
        waitTimeLabel.setFont(new Font("SimSun", Font.PLAIN, 24));
        waitTimeVisible();
        frame.add(waitTimeLabel);


        quitBtn = new JButton("取消");
        quitBtn.setBounds(120,300,120,40);
        quitBtn.setFont(new Font("SimSun",Font.PLAIN ,24));
        quitBtn.addActionListener((e)->{
            myServer.quitWait();
            close();
        });
        frame.add(quitBtn);

        frame.setVisible(true);

    }

    private boolean timeFlag = true;
    public void waitTimeVisible(){
        new Thread(()->{
            long startTime = System.currentTimeMillis();
            long waitTime;
            while (timeFlag){
                long nowTime = System.currentTimeMillis();
                waitTime = nowTime - startTime;
                waitTimeLabel.setText("等待连接：" + waitTime/1000 +" 秒");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


    public void close(){
        frame.dispose();
        timeFlag = false;
    }


    public static void main(String[] args) {



    }



}
